package com.countertack.testcases;

import java.net.InetAddress;
import java.sql.ResultSet;

import com.countertack.impala.ImpalaConnector;
import com.countertack.utils.Configuration;
import com.countertack.utils.HttpClientUtils;
import com.countertack.utils.Utils;
import com.countertack.vmware.VMWareConnector;
import com.countertack.vmware.VMWareUtils;
import com.vmware.vim25.mo.VirtualMachine;

public class VerifyingBasicProcessesExclusion {

	public static void main(String[] args) throws Exception {
		StringBuffer testCaseResult = new StringBuffer();
		ImpalaConnector iConnector = null;
		VMWareConnector esxiConnector = null;
		try {

			if (args.length <= 0) {

				System.out.println("configuration details missed !");
				testCaseResult.append("configuration details missed ! \n");
				return;
			}
			String configFilePath = args[0];

			// String configFilePath =
			// "C:\\Users\\user\\Desktop\\smoketestautomation\\config.properties";

			Configuration.loadProperties(configFilePath);

			String vmUser = Configuration.getProperty("vmuser");
			String vmPassword = Configuration.getProperty("vmpassword");

			iConnector = new ImpalaConnector();
			iConnector.createImpalaConnection(Configuration
					.getProperty("sentinelehost"));

			InetAddress address = InetAddress.getByName(Configuration
					.getProperty("sentinelehost"));
			String sentenelIp = address.getHostAddress();
			System.out.println(address.getHostAddress());
			// connect to esxi and starting virtual machines

			esxiConnector = new VMWareConnector(
					Configuration.getProperty("esxi"));
			// poweredOn
			VirtualMachine endPointMachine = esxiConnector
					.getVirtualMachineByname(Configuration
							.getProperty("vmname"));
			testCaseResult.append("VMName>>>>"
					+ Configuration.getProperty("vmname") + "\n");

			// win7x64-sym-2
			System.out.println("power state >>>"
					+ endPointMachine.getRuntime().powerState);

			String endpointMachineStatus = null;

			// System.out.println("VM Ip Address>>>" + vmIp);
			String smokeSnapShotName = Configuration
					.getProperty("rootsnapshotname");
			esxiConnector.revertToSnapShort(endPointMachine.getSnapshot()
					.getRootSnapshotList(), smokeSnapShotName);

			System.out.println("Reverting to root snap shot>>>>>"
					+ smokeSnapShotName);

			esxiConnector.checkAndRunVirtualMachine(endPointMachine);

			String vmIp = Configuration.getProperty("vmip");
			if (vmIp == null || vmIp.trim() == "") {

				vmIp = endPointMachine.getGuest().ipAddress;
			}
			System.out.println("ip>>>" + endPointMachine.getGuest().ipAddress);
			testCaseResult.append("VM IP>>>>>>" + vmIp + "\n");
			testCaseResult.append("ESXI>>>>>"
					+ Configuration.getProperty("esxi") + "\n");

			String eId = VMWareUtils
					.installKM(Configuration.getProperty("esxi"), null,
							Configuration.getProperty("vmname"), sentenelIp,
							vmIp, vmUser, vmPassword,
							Configuration.getProperty("driverpath"));

			if (eId == null) {

				System.out.println("Unable to install KM");
				testCaseResult.append("Unable to install KM" + "\n");
				return;
			}
			System.out.println("Endpoint id>>>" + eId);
			testCaseResult.append("Endpoint Id>>>>>" + eId + "\n");
			Utils.pauseEndpoint(eId);

			Thread.sleep(60000);

			String payload = "{ "
					+ "  \"type\": \"apply_profile_to_endpoints\", "
					+ "  \"profile\":\""
					+ Configuration.getProperty("profilename") + "\", "
					+ "  \"endpoints\":[ " + "\"" + eId + "\" " + "] " + "} ";

			HttpClientUtils.composePostRequest(
					Configuration.getProperty("restapirooturi")
							+ "/endpoints/command", payload);

			Thread.sleep(3000);

			Utils.resumeEndpoint(eId);

			Thread.sleep(60000);

			String bhid = VMWareUtils.performSmokeTerstOnVM(sentenelIp, vmUser,
					vmPassword, eId, endPointMachine);

			String bhidQuery = "select hex(behaviors.id)  from behaviors INNER JOIN  behaviors_denorm on behaviors.id=behaviors_denorm.behavior_id where behaviors.uri like '%"
					+ eId
					+ "%' and behaviors_denorm.target_process_name like '%cmd.exe%' and behaviors_denorm.behavior_id is not null and behaviors_denorm.target_process_name is not null order by behaviors.event_start_time desc limit 1";
			// verifying process
			ResultSet bhidRes = iConnector
					.executeQueryAndReturnResults(bhidQuery);

			while (bhidRes.next()) {

				bhid = bhidRes.getString(1);

			}

			if (bhid == null) {

				System.out.println("Behavior id is null");
				testCaseResult.append("Behavior id is null \n");
				return;

			}
			testCaseResult.append("Behavior id>>>>>" + bhid + "\n");

			// verifying process
			ResultSet proResset = iConnector
					.executeQueryAndReturnResults("select target_process_name from behaviors_denorm where hex(behavior_id) = '"
							+ bhid
							+ "' and behavior_id is not null and action = 'PROCESS_CREATE' limit 10");

			boolean verProce = true;
			while (proResset.next()) {
				String prosNmae = proResset.getString(1);

				if (prosNmae != null) {
					prosNmae = prosNmae.toLowerCase();
					System.out.println("ProcessName>>>" + prosNmae);
					testCaseResult.append("ProcessName>>>" + prosNmae + "\n");
					if (prosNmae.contains("ipconfig")) {

						verProce = false;

					}

				}
			}

			if (verProce) {

				System.out
						.println("Verifying process exclusion(ipconfig) ---------->Pass");
				testCaseResult
						.append("Verifying process exclusion(ipconfig)---------->Pass \n");

			} else {

				System.out
						.println("Verifying process exclusion(ipconfig)---------->Fail");
				testCaseResult
						.append("Verifying process exclusion(ipconfig)---------->Fail \n");
				// System.exit(0);

			}

		} catch (Exception e) {
			e.printStackTrace();

		} finally {
			try {
				if (esxiConnector != null) {

					esxiConnector.closeEsxiConnection();
				}
			} catch (Exception e) {

				e.printStackTrace();
			}

			try {
				if (iConnector != null) {
					iConnector.closeImpalaConnection();

				}
			} catch (Exception e) {
				e.printStackTrace();

			}
			Utils.addResultsToLog(testCaseResult,
					"verifying_process_exclusion",
					Configuration.getProperty("vmname"));

		}

	}
}
